<!--
 * @Description: 登录-密码校验
 * @FilePath: \hk-computerRoom-Security\src\views\login\component\passwordVerification.vue
 * @Date: 2023-08-10 14:58:28
 * @LastEditTime: 2024-01-31 11:01:16
-->
<template>
	<el-form size="large" :model="state.ruleForm" :rules="state.rules" ref="formRef" class="login-content-form energy-from" @submit.native.prevent>
		<div class="login-animation1">
			<div v-if="state.phoneNumber">
				<!-- <div>密码校验成功!</div> -->
				<div v-if="state.again">已重新向手机号{{ state.phoneNumber }}发送验证码 :</div>
				<div v-else>已向手机号{{ state.phoneNumber }}发送验证码 :</div>
			</div>
			<div v-else>提醒 : 用户信息缺失,请返回重新校验账号密码</div>
		</div>

		<el-form-item label="验证码" class="login-animation2" prop="verifyCode">
			<el-col :span="14">
				<el-input
					text
					maxlength="6"
					placeholder="请输入验证码"
					v-model="state.ruleForm.verifyCode"
					clearable
					autocomplete="off"
					@keyup.native.enter="doLogin(formRef)"
				>
					<template #prefix>
						<el-icon class="el-input__icon"><ele-Position /></el-icon>
					</template>
				</el-input>
			</el-col>
			<el-col :span="1"></el-col>
			<el-col :span="9">
				<el-button type="primary" plain :disabled="state.disabled" @click.prevent="getAgainCode()" v-waves class="login-content-code">{{
					state.text
				}}</el-button>
			</el-col>
		</el-form-item>

		<div class="login-animation3">
			<el-button round type="primary" v-waves class="login-content-submit" :loading="state.loading.signIn" @click.prevent="doLogin(formRef)">
				<span>{{ $t('message.mobile.btnText') }}</span>
			</el-button>
			<div class="login-msg" v-waves>
				<div>温馨提示 :</div>
				<div>如长时间未收到短信验证码,请联系管理人员核对手机号是否正确</div>
			</div>
		</div>
		<!-- <el-button text type="primary" v-waves @click.prevent="emit('refresh')">
			<el-icon style="font-size: 16px"><Back /></el-icon>
			返回
		</el-button> -->
	</el-form>
</template>

<script setup lang="ts" name="loginMobile">
import { reactive, ref, computed, onMounted } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
// import { Back } from '@element-plus/icons-vue';
// import { useLoginApi } from '/@/api/login';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { useUserInfo } from '/@/stores/userInfo';
import pinia from '/@/stores/index';
import { Session } from '/@/utils/storage';
import { formatAxis } from '/@/utils/formatTime';
import { useRoute, useRouter } from 'vue-router';
import { NextLoading } from '/@/utils/loading';
import {isNull} from '/@/utils/other'
import { useI18n } from 'vue-i18n';
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const formRef = ref<FormInstance>();
const route = useRoute();
const router = useRouter();
const { t } = useI18n();
// const emit = defineEmits(['refresh']);
// 定义变量内容
const state: any = reactive({
	again: false,
	phoneNumber: '',
	time: 60, // 倒计时时间
	text: '60s后获取验证码',
	disabled: false, // 禁用倒计时按钮
	timer: null, // 定时器
	code: '', // 验证码
	ruleForm: {
		username: '',
		password: '',
		// phone: '',
		verifyCode: '', // 验证码
	},
	rules: {
		verifyCode: [
			{ required: true, message: '请输入6位数字验证码', trigger: 'blur' },
			{ max: 6, message: '验证码长度为6位', trigger: 'blur' },
		],
	},
	loading: {
		signIn: false,
	},
});

onMounted(() => {
	const userBasicInfo = Session.get('userBasicInfo');
  console.log(userBasicInfo)
  if(userBasicInfo!=null){
	state.phoneNumber = userBasicInfo.phoneNumber.replace(/\d{4}(?=\d{4}$)/, '****');
	state.ruleForm = {
		username: userBasicInfo.username,
		password: userBasicInfo.password,
		verifyCode: '', // 验证码
	};
	startCountdown();
  }

	// 监听键盘按下事件
	// document.addEventListener('keydown', function (event) {
	// 	// 检查按下的键是否是回车键（键码为13）
	// 	if (event.keyCode === 13) {
	// 		// 在这里执行你希望触发的事件逻辑
	// 		event.preventDefault(); // 可选：阻止回车键的默认行为，比如防止表单提交
	// 		console.log('回车键被按下了！');
	// 		// 调用你的函数或处理其他操作
	// 	}
	// });
});

// 开始倒计时
const startCountdown = () => {
	state.disabled = true;
	state.text = state.time + 's后重新获取';

	state.timer = setInterval(() => {
		state.time--;
		state.text = state.time + 's后重新获取';
		if (state.time < 0) {
			clearInterval(state.timer);
			state.text = '获取验证码';
			state.time = 60;
			state.disabled = false;
		}
	}, 1000);
};

// 再次获取验证码
const getAgainCode = async () => {
	state.again = true;
	state.ruleForm.verifyCode = '';
	startCountdown();
	await useUserInfo(pinia).setUserInfos({
		username: state.ruleForm.username,
		password: state.ruleForm.password,
	});
};

// 点击登录
const doLogin = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	// 表格验证
	await formEl.validate(async (valid: any) => {
		if (valid) {
			state.loading.signIn = true;
			setTimeout(() => {
				state.loading.signIn = false;
			}, 1000);

			await useUserInfo(pinia).setUserInfos(state.ruleForm);

			// 存储 token 到浏览器缓存
			// Session.set('token', Math.random().toString(36).substr(0));
			if (!themeConfig.value.isRequestRoutes) {
				// 前端控制路由，2、请注意执行顺序
				const isNoPower = await initFrontEndControlRoutes();
				signInSuccess(isNoPower);
			} else {
				// 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
				// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
				const isNoPower = await initBackEndControlRoutes();
				// 执行完 initBackEndControlRoutes，再执行 signInSuccess
				signInSuccess(isNoPower);
			}
		} else {
			// 关闭 loading
			state.loading.signIn = false;
			ElMessage.warning('请先填写验证码');
		}
	});
};

// 登录成功后的跳转
const signInSuccess = (isNoPower: boolean | undefined) => {
	if (isNoPower) {
		ElMessage.warning('抱歉，您没有登录权限');
		Session.clear();
	} else {
		// 初始化登录成功时间问候语
		let currentTimeInfo = currentTime.value;
		// 登录成功，跳到转首页
		// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
		if (route.query?.redirect) {
			router.push({
				path: <string>route.query?.redirect,
				query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
			});
		} else {
			router.push('/');
		}
		// 登录成功提示
		const signInText = t('message.signInText');
		ElMessage.success(`${currentTimeInfo}，${signInText}`);
		// 添加 loading，防止第一次进入界面时出现短暂空白
		NextLoading.start();
	}
	state.loading.signIn = false;
};

// 时间获取
const currentTime = computed(() => {
	return formatAxis(new Date());
});
</script>

<style scoped lang="scss">
.login-content-form {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	margin-top: 20px;
	@for $i from 1 through 4 {
		.login-animation#{$i} {
			opacity: 0;
			animation-name: error-num;
			animation-duration: 0.5s;
			animation-fill-mode: forwards;
			animation-delay: calc($i/10) + s;
		}
	}

	.login-animation1 {
		display: flex;
		flex-direction: column;
		color: #8daaf7;
		font-size: 18px;
	}

	.login-animation2 {
		margin: 50px 0px;
	}

	.login-animation3 {
		flex: 1;
		.login-content-submit {
			width: 100%;
			letter-spacing: 2px;
			font-weight: 300;
			margin-bottom: 20px;
		}
		.login-msg {
			color: var(--el-text-color-placeholder);
			font-size: 14px;
			margin-bottom: 20px;
		}
	}

	.login-content-code {
		width: 120%;
	}

	:deep(.login-content-code, .el-button--success.is-link, .el-button--success.is-plain, .el-button--success.is-text) {
		--el-button-bg-color: transparent;
		--el-button-hover-bg-color: #0d3282;
	}

	:deep(.el-button.is-disabled, .el-button.is-disabled:focus, .el-button.is-disabled:hover) {
		background-color: #0d3282;
		border-color: #7281a4;
	}
}
</style>
